package com.atguigu.order.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.atguigu.clients.ProductClient;
import com.atguigu.order.mapper.OrderMapper;
import com.atguigu.order.service.OrderService;
import com.atguigu.param.OrderParam;
import com.atguigu.param.PageParam;
import com.atguigu.param.ProductIdsParam;
import com.atguigu.param.ProductNumberParam;
import com.atguigu.pojo.Order;
import com.atguigu.pojo.Product;
import com.atguigu.utils.R;
import com.atguigu.vo.AdminOrderVo;
import com.atguigu.vo.CartVo;
import com.atguigu.vo.OrderVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ProductClient client;

    @Transactional
    @Override
    public R save(OrderParam orderParam) {

        // 已结算的购物车id列表
        List<Integer> cartIds = new ArrayList<>();
        // 已结算的商品（id和销量）列表
        ArrayList<ProductNumberParam> productNumberParams = new ArrayList<>();
        // 插入订单数据库的列表
        ArrayList<Order> orders = new ArrayList<>();

        Integer userId = orderParam.getUserId();
        List<CartVo> products = orderParam.getProducts();
        // 订单编号用时间戳
        long ctime = System.currentTimeMillis();
        //收集数据
        for (CartVo cartVo : products) {

            cartIds.add(cartVo.getId());

            ProductNumberParam productNumberParam = new ProductNumberParam();
            productNumberParam.setProductId(cartVo.getProductID());
            productNumberParam.setProductNum(cartVo.getNum());
            productNumberParams.add(productNumberParam);

            Order order = new Order();
            order.setOrderId(ctime);
            order.setOrderTime(ctime);
            order.setProductId(cartVo.getProductID());
            order.setProductNum(cartVo.getNum());
            order.setProductPrice(cartVo.getPrice());
            order.setUserId(userId);
            orders.add(order);

        }
        // 批量插入数据
        this.saveBatch(orders);

        // rabbitmq异步通信
        // 商品服务要增加对应商品的销量和减少对应商品的库存
        rabbitTemplate.convertAndSend("topic.ex","sub.number",productNumberParams);
        // 购物车服务要清空对应购物车项的信息
        rabbitTemplate.convertAndSend("topic.ex","clear.cart",cartIds);

        return R.ok("订单生成成功");
    }

    @Override
    public R list(Integer userId) {

        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<Order> orderList = this.list(queryWrapper);


        // 收集对应的商品集合
        HashSet<Integer> set = new HashSet<>();
        for (Order order : orderList) {
            set.add(order.getProductId());
        }
        ProductIdsParam productIdsParam = new ProductIdsParam();
        productIdsParam.setProductIds(new ArrayList<Integer>(set));

        Object data = client.ids(productIdsParam).getData();
        String json = JSONObject.toJSONString(data);
        List<Product> products = JSONObject.parseObject(json, new TypeReference<List<Product>>(){});
        Map<Integer, Product> map = products.stream().collect(Collectors.toMap(Product::getProductId, v -> v));


        // 分组
        Map<Long, List<Order>> collect = orderList.stream().collect(Collectors.groupingBy(Order::getOrderId));

        // 收集结果
        List<List<OrderVo>> result =new ArrayList<>();
        for (List<Order> orders : collect.values()) {
            List<OrderVo> orderVos =new ArrayList<>();
            for (Order order : orders) {

                OrderVo orderVo = new OrderVo();
                Product product = map.get(order.getProductId());
                orderVo.setProductName(product.getProductName());
                orderVo.setProductPicture(product.getProductPicture());
                orderVo.setId(order.getId());
                orderVo.setOrderId(order.getOrderId());
                orderVo.setOrderTime(order.getOrderTime());
                orderVo.setProductNum(order.getProductNum());
                orderVo.setProductId(order.getProductId());
                orderVo.setProductPrice(order.getProductPrice());
                orderVo.setUserId(order.getUserId());

                orderVos.add(orderVo);
            }
            result.add(orderVos);


        }
        return R.ok("查询成功",result);
    }

    @Override
    public R adminList(PageParam pageParam) {

        int offset = (pageParam.getCurrentPage()-1)*pageParam.getPageSize();
        int number = pageParam.getPageSize();
        Long total = orderMapper.selectCount(null);

        List<AdminOrderVo> adminOrderVoList= orderMapper.selectAdminOrderVoList(offset,number);

        return R.ok("订单查询成功",adminOrderVoList,total);
    }
}
